/**
 * 模拟实现
 * HashMap
 */

// key-value 模型
public class HashBucket {

    public HashBucket() {
        // write code here
    }
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[] array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(int key, int value) {
        // write code here
        if (array == null || loadFactor() >= LOAD_FACTOR) {
            resize();
        }
        Node node = new Node(key, value);
        int index = key % array.length;
        if (array[index] == null) {
            array[index] = node;
        }else {
            Node cur = array[index];
            Node curP = null;
            while (cur != null) {
                if (node.key == cur.key) {
                    cur.value = value;
                    return;
                }
                curP = cur;
                cur = cur.next;
            }
            curP.next = node;
        }
    }

    private void resize() {
        // write code here
        if (array == null) {
            array = new Node[DEFAULT_SIZE];
            return;
        }
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                Node cur = array[i];
                while (cur != null) {
                    Node curN = cur.next;
                    int key = cur.key;
                    int newIndex = key % newArray.length;
                    cur.next = newArray[newIndex];
                    newArray[newIndex] = cur;
                    cur = curN;
                }
            }
        }
        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public Node get(int key) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];
        if (array[index] == null) {
            return null;
        }
        while (cur != null) {
            if (cur.key == key) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }
}